package labox.innovation.gameserver.model.zone.form;

import labox.innovation.gameserver.model.zone.L2ZoneForm;

/**
 * 长方体地带，一个标准的矩形地带形式
 *
 *
 * @author  durgus
 */
public class ZoneCuboid extends L2ZoneForm {

	private int _x1, _x2, _y1, _y2;

	public ZoneCuboid(int x1, int x2, int y1, int y2) {
		_x1 = x1;
		_x2 = x2;
		if (_x1 > _x2) // switch them if alignment is wrong
		{
			_x1 = x2;
			_x2 = x1;
		}

		_y1 = y1;
		_y2 = y2;
		if (_y1 > _y2) // switch them if alignment is wrong
		{
			_y1 = y2;
			_y2 = y1;
		}
	}

	@Override
	public boolean isInsideZone(int x, int y) {
		return !(x < _x1 || x > _x2 || y < _y1 || y > _y2);
	}

	@Override
	public boolean intersectsRectangle(int ax1, int ax2, int ay1, int ay2) {
		// Check if any point inside this rectangle
		if (isInsideZone(ax1, ay1))
			return true;
		if (isInsideZone(ax1, ay2))
			return true;
		if (isInsideZone(ax2, ay1))
			return true;
		if (isInsideZone(ax2, ay2))
			return true;

		// Check if any point from this rectangle is inside the other one
		if (_x1 > ax1 && _x1 < ax2 && _y1 > ay1 && _y1 < ay2)
			return true;
		if (_x1 > ax1 && _x1 < ax2 && _y2 > ay1 && _y2 < ay2)
			return true;
		if (_x2 > ax1 && _x2 < ax2 && _y1 > ay1 && _y1 < ay2)
			return true;
		if (_x2 > ax1 && _x2 < ax2 && _y2 > ay1 && _y2 < ay2)
			return true;

		// Horizontal lines may intersect vertical lines
		if (lineSegmentsIntersect(_x1, _y1, _x2, _y1, ax1, ay1, ax1, ay2))
			return true;
		if (lineSegmentsIntersect(_x1, _y1, _x2, _y1, ax2, ay1, ax2, ay2))
			return true;
		if (lineSegmentsIntersect(_x1, _y2, _x2, _y2, ax1, ay1, ax1, ay2))
			return true;
		if (lineSegmentsIntersect(_x1, _y2, _x2, _y2, ax2, ay1, ax2, ay2))
			return true;

		// Vertical lines may intersect horizontal lines
		if (lineSegmentsIntersect(_x1, _y1, _x1, _y2, ax1, ay1, ax2, ay1))
			return true;
		if (lineSegmentsIntersect(_x1, _y1, _x1, _y2, ax1, ay2, ax2, ay2))
			return true;
		if (lineSegmentsIntersect(_x2, _y1, _x2, _y2, ax1, ay1, ax2, ay1))
			return true;
		if (lineSegmentsIntersect(_x2, _y1, _x2, _y2, ax1, ay2, ax2, ay2))
			return true;

		return false;
	}

	@Override
	public double getDistanceToZone(int x, int y) {
		double test, shortestDist = Math.pow(_x1 - x, 2) + Math.pow(_y1 - y, 2);

		test = Math.pow(_x1 - x, 2) + Math.pow(_y2 - y, 2);
		if (test < shortestDist)
			shortestDist = test;

		test = Math.pow(_x2 - x, 2) + Math.pow(_y1 - y, 2);
		if (test < shortestDist)
			shortestDist = test;

		test = Math.pow(_x2 - x, 2) + Math.pow(_y2 - y, 2);
		if (test < shortestDist)
			shortestDist = test;

		return Math.sqrt(shortestDist);
	}
}
